import Taro, { Component } from '@tarojs/taro'
import {View, Image, Text, Button} from '@tarojs/components'
import { connect } from '@tarojs/redux'
import * as actions from '@actions/user'
import jump from '@utils/jump'
import { CDN } from '@constants/api'
// NOTE 使用统一接口的多端文件进行跨端处理
// auth 中有 index.js/index.weapp.js/index.alipay.js
// 若是编译微信，则实际引入的是 index.weapp.js
// 若是编译 H5，因为不存在 index.h5.js，所以引入的是默认的 index.js
import './userLogin.scss'
import weapp from '@assets/weapp.png'

const LOGO = `${CDN}/a7ba557fde54270c71656222c7837396.png`

@connect(state => state.user, actions)
class UserLogin extends Component {
  config = {
    navigationBarTitleText: '登录'
  }

  constructor(props) {
    super(props)
    this.state = {
    }
    this.returnPage = this.$router.params.returnPage
  }

  componentWillMount() {
    this.updateCode()
  }

  updateCode() {
    Taro.login().then((res) => {
      Taro.setStorageSync('code', res.code)
    })
  }

  getPhoneNumber = (e) => {
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      Taro.checkSession({
        success () {},
        fail () {
          this.updateCode()
        }
      })

      const payload = {
        code: Taro.getStorageSync('code'),
        iv: e.detail.iv,
        encryptedData: e.detail.encryptedData
      }

      Taro.showLoading();
      this.props.dispatchLogin(payload)
        .then(() => {
          if (this.returnPage) {
            Taro.redirectTo({
              url: this.returnPage
            })
          } else {
            Taro.navigateBack({ delta: 1 })
          }
        }).catch(() => {
          Taro.showToast({
            title: '微信登录失败',
            icon: 'none'
          })
      })
      Taro.hideLoading();
    }
  }

  render () {

    return (
      <View className='user-login'>
        <View className='user-login__logo'>
          {/*<Image src={LOGO} className='user-login__logo-img' />*/}
        </View>

        <Button type='primary' className='user-login__btn' openType='getPhoneNumber' onGetPhoneNumber={this.getPhoneNumber}>
          <Image className='user-login__btn-img' src={weapp} />
          <Text className='user-login__btn-txt'>微信一键登录</Text>
        </Button>

      </View>
    )
  }
}

export default UserLogin
